package com.ljb.smartinspector;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sensoro.beacon.kit.Beacon;
import com.sensoro.beacon.kit.BeaconManagerListener;
import com.sensoro.cloud.SensoroManager;

import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 0;
    SensoroManager sensoroManager;
    App app;
    BeaconManagerListener beaconManagerListener;
    private BluetoothAdapter bluetoothAdapter;
    private boolean blueToothState;
    private BroadcastReceiver receiver;
    CopyOnWriteArrayList<Beacon> beacons;
    private TextView tv;
    private LinearLayout container;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requirePermission();
        initCtrl();
        initSensoroListener();
        initBroadcast();
    }

    //权限请求
    private void requirePermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            // 业务逻辑
        } else {
            // 是否应该给用户提示说明？
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    // 异步方式提示用户，不要阻塞在这等待用户响应。当用户看到提示之后，尝试重新获取权限
                    Log.e(TAG, "Show an expanation to the user *asynchronously*");
                } else {
                    // 不需要提示说明，直接获取权限
                    Log.e(TAG, "// No explanation needed, we can request the permission.");
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
                }
            } else {
                // 业务逻辑
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 用户授权成功
                    Log.e(TAG, "permission was granted");
                    // 业务逻辑
                } else {
                    // 申请权限被用户拒绝，相关功能不可使用
                    Log.e(TAG, "permission denied");
                }
            }
            // 其他 'case' 可能是 App 申请的其他权限
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        blueToothState = bluetoothAdapter.isEnabled();
        if (blueToothState) {
            startSensoroService();
        } else {
            bluetoothAdapter.enable();
        }
    }

    private void openBluetooth() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setNegativeButton("打开蓝牙", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                bluetoothAdapter.enable();
            }
        }).setTitle("巡检服务需要您打开蓝牙").setCancelable(false);
        builder.show();
    }

    private void initBroadcast() {
        Log.e(TAG, "initBroadcast: 注册蓝牙监听广播");
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

        receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                String action = intent.getAction();

                if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                    int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                            BluetoothAdapter.ERROR);
                    switch (state) {
                        case BluetoothAdapter.STATE_OFF:
                            openBluetooth();
                            break;
                        case BluetoothAdapter.STATE_ON:
                            startSensoroService();
                            break;
                    }
                }
            }
        };
        registerReceiver(receiver, filter);
    }

    //开始云子服务
    private void startSensoroService() {
        sensoroManager.setBeaconManagerListener(beaconManagerListener);
        try {
            sensoroManager.startService();
            Log.e(TAG, "startSensoroService: 云子服务已启动");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //初始化云子监听器
    private void initSensoroListener() {
        beaconManagerListener = new BeaconManagerListener() {
            @Override
            public void onNewBeacon(Beacon beacon) {
                Log.e(TAG, "onNewBeacon: 发现新的iBeacon" + beacon.getSerialNumber());
                if (!beacons.contains(beacon)) {
                    beacons.add(beacon);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showBeacons();
                        }
                    });
                }
            }

            @Override
            public void onGoneBeacon(Beacon beacon) {
                Log.e(TAG, "onGoneBeacon: iBeacon消失" + beacon.getSerialNumber());
                if (beacons.contains(beacon)) {
                    beacons.remove(beacon);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showBeacons();
                        }
                    });
                }
            }

            @Override
            public void onUpdateBeacon(ArrayList<Beacon> arrayList) {

            }
        };
    }

    private void showBeacons() {
        container.removeAllViews();
        for (Beacon beacon : beacons) {
            String serialNumber = beacon.getSerialNumber();
            TextView textView = new TextView(this);
            textView.setPadding(10, 20, 10, 20);
            textView.setText(serialNumber);
            textView.setTag(beacon);
            textView.setOnClickListener(this);
            container.addView(textView);
        }
    }

    //初始化控制器
    private void initCtrl() {
        tv = (TextView) findViewById(R.id.tv);
        container = (LinearLayout) findViewById(R.id.ll_container);

        app = (App) getApplication();
        sensoroManager = app.sensoroManager;
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        beacons = new CopyOnWriteArrayList<>();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sensoroManager != null) {
            sensoroManager.stopService();
            sensoroManager = null;
            Log.e(TAG, "onDestory: 云子服务已停止");
        }
        unregisterReceiver(receiver);
    }

    @Override
    public void onClick(View v) {
        TextView view = (TextView) v;
        CharSequence text = view.getText();
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, BeaconSettingActivity.class);
        intent.putExtra("iBeaconSN", text);
        intent.putExtra("iBeacon", (Beacon) view.getTag());
        startActivity(intent);
    }
}
